package me.magicall.test.reflect.proxy;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.List;


public class Main {
	public static void main(final String[] args) {
		equals();

//		serialize();
	}

	static List<User> getList() {
		final UserDao dao = getDao();
		return dao.getList();
	}

	static User getByKey(final int id) {
		final UserDao dao = getDao();
		final User byKey = dao.getByKey(id);
		return byKey;
	}

	static User getByKey() {
		return getByKey(1);
	}

	static void equals() {
		final User u1 = getByKey();
		final User u2 = getByKey();
		final Object xiao3 = new Object();
		System.out.println("@@@@@@u1.equals(u1):should be true:" + u1.equals(u1));
		System.out.println("@@@@@@u1.equals(xiao3):should be false:" + u1.equals(xiao3));
		System.out.println("@@@@@@u1.equals(u2):should be true:" + u1.equals(u2) + " u2.equals(u1):should be true:" + u2.equals(u1));
		final List<User> list = getList();
		for (int i = 0; i < list.size(); i++) {
			final User u = list.get(i);
			for (int j = i + 1; j < list.size(); j++) {
				final User uu = list.get(j);
				System.out.println("@@@@@@" + u + " " + uu + " " + u.equals(uu));
			}
		}
	}

	static void serialize() {
		final User byKey = getByKey();
		System.out.println("main:" + byKey);

		ObjectOutputStream out = null;
		ObjectInputStream in = null;
		try {
			final ByteArrayOutputStream arrOut = new ByteArrayOutputStream();
			out = new ObjectOutputStream(arrOut);
			out.writeObject(byKey);
			System.out.println("@@@@@@" + arrOut.size());

			final InputStream arrIn = new ByteArrayInputStream(arrOut.toByteArray());
			in = new ObjectInputStream(arrIn);
			System.out.println("@@@@@@" + in.readObject());
		} catch (final IOException e) {
			e.printStackTrace();
		} catch (final ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (final IOException e) {
					e.printStackTrace();
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (final IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	static UserDao getDao() {
		final InvocationHandler h = new DaoImplProxy();
		final Object o = Proxy.newProxyInstance(Main.class.getClassLoader(), new Class[] { UserDao.class }, h);
		final UserDao dao = (UserDao) o;
		return dao;
	}
}
